<script setup lang="ts">

import {computed, inject, provide, ref, watch, reactive} from "vue";
import BaseInfo from "./components/baseInfo.vue";
import RouteInfo from "@/views/components/routeInfo.vue";
import ServiceInfo from "./components/serviceInfo.vue";
import ChargeInfo from "./components/chargeInfo.vue";
import ParcelInfo from "./components/parcelInfo.vue";
import CleranceInfo from "./components/cleranceInfo.vue";
import OperateInfo from "./components/operateInfo.vue";
import Attachment from "@/views/components/attachment.vue";
import AttachmentPod from "@/views/components/attachmentPod.vue";
import workorder from "@/views/components/WorkOrder.vue";
import sendorder from "@/views/document/shipment/components/SendOrder.vue";
import DeliveryInfo from "./components/deliveryInfo.vue";
import CasesInfo from "@/views/document/shipment/components/casesInfo.vue";
import PodInfo from "@/views/document/shipment/components/podInfo.vue";
import ProfitInfo from "@/views/document/shipment/components/profitInfo.vue";
import CostInfo from "@/views/components/costInfo.vue";
import InComeInfo from "@/views/components/inComeInfo.vue";
import CommissionInfo from "@/views/components/commissionInfo.vue";
import ExpenseInfo from "@/views/components/expenseInfo.vue";
import shipment from "@/api/document/shipment";
import {Message} from "@arco-design/web-vue";
import printLabel from "@/api/logistics/printLabel";
import BatchActionModal from "@cps/actionsNew/batchActionModal.vue";
import declareColumns from "@/utils/shipmentTools";
import {auth} from '@/utils/common'
import AddModal from "@cps/actions/addModal.vue";
import dicthelp from "@/utils/dicthelp.js";
import {request} from "@/utils/request.js";
import tool from '@/utils/tool'
const addModalRef = ref()
const dataVisible = ref(false)
const record = ref({id: null,})
const invoicesType = ref('shipment')
const originalDeclareColumns = ref([])
const crudRef = inject('crudRef')
const dataList = inject('dataList')
const tableList = inject('tableList')
const span = ref(12)
const routeSpan = ref(6)
const routeInfo = ref({type: "shipment", about_type: 'App\\Document\\Model\\Shipment'})
const fileData = ref({type: 1, span: 12})
const workOrderData = ref({type: 1, span: 12})
const getRecord = () => {
  if (!record.value.id) {
    return
  }
  shipment.read(record.value.id).then(async result => {
    record.value = result.data
    detailLoading.value = false
    for(let i = 0 ; i < record.value?.parcel_declaration.length ;i++){
      let item=record.value.parcel_declaration[i]
      item.is_elec = item.is_elec == 1 ? '是':'否'
      item.is_magnetic = item.is_magnetic == 1 ? '是':'否'
  }
    originalDeclareColumns.value = await declareColumns.getDeclareColumns(record.value.service_id)
  });

  // if(refreshList){
  //   crudRef.value.refresh()
  // }
}
const detailLoading = ref(true)

const onShow = async (data) => {
  record.value.id = data.id
  detailLoading.value = true
  dataVisible.value = true
  getRecord();
}
const title = computed(() => {
  const list = []
  const fields = [
    'shipment_no',
    'client_reference',
    'self_reference',
    'ext_number',
    'user'
  ];
  for (const field of fields) {
    if (record.value[field]) {
      if ([field] == 'user') {
        list.push(record.value[field].username)
      } else {
        list.push(record.value[field])
      }
    }
  }
  return "# " + list.join('/')
})
const close = () => {
  dataVisible.value = false
  tableList()
}
const cancel = async () => {
  let res = await shipment.cancel({ids: record.value.id})
  if (!res.success) {
    Message.error(res.message || '失败');
    return
  }
  Message.success(res.message || '成功');
  // crudRef.value.refresh();
  await getRecord()
}
const openLabel = () => {
  batchActionRef.value.open({title: '系统标签', api: printLabel.preview, isPrint: true})
}
const downloadInfo = () =>{
  let data = {id:record.value.id}
      const download = (url) => request({url,data , method: 'post', timeout: 60 * 1000, responseType: 'blob'})
     download('document/shipment/execlInfo').then(res => {
        tool.download(res)
        Message.success('请求成功，文件开始下载')
      }).catch((res) => {
        res.text().then((text) => {
          Message.error(JSON.parse(text).message)
        })
      })
}
const colGap = ref(6)
const rowGap = ref(6)
const batchActionRef = ref()
const selected = computed(() => [record.value.id])
const changeUser = () => {
  addModalRef.value.open(reactive([
    {
      title: "用户",
      dataIndex: "user_id",
      addDefaultValue: record.value.user_id,
      formType: "select",
      dict: dicthelp.customer,
      required: true,
      virtualListProps: {},
    },
    {
      dataIndex: "id",
      addDefaultValue: record.value.id,
      addDisplay: false,
      addDisabled: true
    }
  ]), {
    viewType: 'modal',
  }, shipment.updateCustomer, '修改用户', function name() {
    getRecord()
    // crudRef.value.refresh()
  })
}

provide('originalDeclareColumns', originalDeclareColumns)
provide('span', span)
provide('invoicesType', invoicesType)
provide('getRecord', getRecord)
provide('colGap', colGap)
provide('rowGap', rowGap)
provide('record', record)
provide('routeInfo', routeInfo)
provide('routeSpan', routeSpan)
provide('fileData', fileData)
provide('workOrderData', workOrderData)
defineExpose({onShow, getRecord})
</script>

<template>
  <a-drawer :visible="dataVisible" width="80%" class="gt-drawer" @cancel="close"
            :footer="false"
            v-if="dataVisible"
            unmount-on-close>
    <a-spin v-if="detailLoading" :loading="detailLoading" tip="数据加载中..." style="text-align: center;display: block;margin-top: 100px;">
    </a-spin>

    <add-modal ref="addModalRef"></add-modal>
    <template #title>
      <div class="grid grid-cols-[minmax(0,1fr),auto] items-center" v-if="!detailLoading">
        <div>{{ title }}</div>
        <div>
          <!--          <a-button><icon-download />下载发票</a-button>-->
          <a-button v-show="record?.created_by > 0 && record?.status == 1" @click="changeUser()">
            <icon-user/>
            修改用户
          </a-button>
          <!--          <a-button><icon-download />导出运单</a-button>-->
          <a-popconfirm
              content="确定要删除数据吗?"
              position="bottom"
              @ok="cancel"
              v-if="record?.status == 1"
          >
            <a-button
                v-auth="['document:shipment:cancel']"
                status="danger" type="primary" v-if="record?.status != 2">
              <icon-delete/>
              取消
            </a-button>

          </a-popconfirm>
          <a-button @click="openLabel" v-auth="['logistics:printLabel:preview']">
            <icon-printer/>
            系统标签
          </a-button>
          <a-button @click="downloadInfo" v-auth="['document:shipment:execlInfo']">
            <icon-download/>
            下载运单
          </a-button>
        </div>
      </div>
    </template>
    <a-space direction="vertical" class="w-full" v-if="!detailLoading">
      <a-grid :colGap="colGap" :rowGap="rowGap">
        <service-info/>
        <charge-info/>
        <base-info/>
        <route-info/>
        <parcel-info v-if="auth('document:parcel:index')"/>
        <cleranceInfo v-if="auth('document:parcelDeclaration:index')"/>
        <profit-info v-if="auth('document:shipment:viewProfit')"/>
        <in-come-info v-if="auth('finance:customerFee:index')"/>
        <expense-info v-if="auth('finance:supplierFee:index')"/>
        <cost-info v-if="auth('finance:cost:index')"/>
        <commission-info v-if="auth('finance:bonus:index')"/>
        <!--   todo 完善展示      -->
        <!--        <operateInfo />-->
        <attachment v-if="auth('document:attachment:index')"/>
        <attachment-pod v-if="auth('logistics:attachmentPod:index')"/>
        <workorder v-if="auth('logistics:workOrder:index')"/>
        <sendorder v-if="auth('document:sendOrder:index')" v-show="record?.status > 1"/>
        <!--        <delivery-info />-->
        <!--        <casesInfo />-->
        <!--        <podInfo />-->
      </a-grid>
    </a-space>
    <batch-action-modal :crud-ref="crudRef"
                        :selected="selected"
                        :dataList="dataList"
                        ref="batchActionRef"
    ></batch-action-modal>

  </a-drawer>

</template>

<style lang="less">
.gt-drawer .arco-drawer-body {
  background-color: var(--color-neutral-2);
  color: var(--color-text-2);
}

.basInfo td {
  padding-bottom: 3px !important;
}
</style>